import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import useDashboardStore from '../stores/module/dashboard'
import useUserStore from '../stores/module/user';
class WebSocketService {
    // 存储WebSocket实例
    socket: any = null;
    // 存储连接状态，使用Vue 3的ref创建响应式数据
    connected = ref(false);
    // 存储接收到的消息，同样使用ref创建响应式数据
    messages = ref();
    connect(sheetId?: any) {
        this.socket = new WebSocket(`ws://localhost:3000?default=1&id=${JSON.parse(localStorage.getItem('user') as string)._id}&name=${JSON.parse(localStorage.getItem('user') as string).username}&sheetId=${sheetId ? sheetId : null}`);
        this.socket.onopen = this.onOpen.bind(this);
        this.socket.onmessage = this.onMessage.bind(this);
        this.socket.onclose = this.onClose.bind(this);
        this.socket.onerror = this.onError.bind(this);
    }

    onOpen() {
        this.connected.value = true;
    }

    onMessage(event: { data: string; }) {
        const message = JSON.parse(event.data);
        if (message.type == 0 || message.type == 1) {
            this.messages.value = message
            const dashboardStore = useDashboardStore();
            dashboardStore.unreadCount += 1
            ElMessage.success('您有一条新的消息')
        }
    }

    onClose(event: any) {
        this.connected.value = false;
        console.log('WebSocket连接已关闭', event);
    }

    onError(event: any) {
        console.error('WebSocket发生错误', event);
    }

    send(message: any) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.error('WebSocket未处于打开状态，无法发送消息');
        }
    }

    close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default new WebSocketService()